<template>
  <a-modal
    title="操作"
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading" v-if="setShow">
      <a-form :form="form">
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="商户">
          <a-select :disabled="display"
            v-decorator="[ 'merchantId', {rules: [{ required: true, message: '请选择服务商' }],initialValue: defaultCompany}]"
            placeholder="请选择服商户">
            <a-select-option :value="company.id" v-for="company in companyList" :key="company.id">
              {{company.name}}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="门店名称"
        >
          <a-input placeholder="门店名称"
                   v-decorator="[ 'name', {rules: [{ required: true, message: '请输入。。。' }]} ]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="省市区"
        >
          <a-cascader placeholder="省市区" :options="options" @change="onChange"
                      v-decorator="[ 'area', {rules: [{ required: true, message: '请输入。。。' }]} ]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="门店地址"
        >
          <a-input placeholder="门店地址" v-decorator="[ 'address', {rules: [{ required: true, message: '请输入。。。' }] }]"/>
        </a-form-item>

      </a-form>
    </a-spin>
<!--   设备管理 -->
    <a-spin :spinning="confirmLoading" v-if="!setShow">
        <a-form :form="form">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="已分配设备"
          >
            <a-table :pagination="false"  :dataSource="dataSource" :columns="columns" style="font-size: 60px">
              <template slot="name" slot-scope="text, record">
                <editable-cell :text="text" />
              </template>
              <template slot="operation" slot-scope="text, record">
                <a-popconfirm
                  v-if="dataSource.length"
                  title="确认删除?"
                  @confirm="() => onDelete(record.id)">
                  <a href="javascript:;">X</a>
                </a-popconfirm>
              </template>
            </a-table>
          </a-form-item>
          <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="未分配设备">
            <a-select allowClear
                      showSearch
                      optionFilterProp="children"
                      :filterOption="filterOption"
                      v-decorator="[ 'deviceId', {rules: [{ required: false, message: '请选择未分配设备' }]}]"
                      placeholder="请选择未分配设备">
              <a-select-option :value="device.id" v-for="device in deviceList" :key="device.id">
                {{device.deviceNo}}{{device.storeName}}
              </a-select-option>
            </a-select>
          </a-form-item>


        </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { save ,setSelectAll,addStoreDevice,selectAllArea,selectDeviceList,deleteStroeDevice} from '@/api/storeService/store'
  import { selectAll} from '@/api/merchantService/merchant'
  import pick from 'lodash.pick'

  export default {
    //--############  data() ###############-->
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        visible: false,
        confirmLoading: false,
        mdl: {
          area:[]
        },
        form: this.$form.createForm(this),
        companyList:[],
        deviceList:[],
        defaultCompany:[],
        isDisabled: false,
        setShow:true,
        options: [],
        display:false,
        areas:[],
        dataSource: [
          {
            id: '0',
            modelNo: '',
            deviceNo:''

          }, {
            id: '1',
            modelNo: '',
            deviceNo: '',

          }],
        columns: [
          {
            title: '设备厂家',
            dataIndex: 'modelNo',
            width: '30%',
            // scopedSlots: { customRender: 'name' },
          }, {
            title: '设备号',
            dataIndex: 'deviceNo',
            width:'50%'
          }, {
            title: '删除',
            dataIndex: 'operation',
            width:'15%',
            scopedSlots: { customRender: 'operation' },
          }],
      }
    },
    //--############  data() ###############-->

    mounted() {
      selectAll().then(res => {
        this.companyList = res.result
        this.defaultCompany = this.companyList[0].id
        this.company = {
          'companyId': this.defaultCompany,
          'sourceType': 'bigWheel'
        }
      });
      selectAllArea().then(res =>{ //查询省市区
          this.options = res.result;
        }
      )
      // this.$nextTick(()=>{
      //
      // })
      this.setAll()


    },

    //--############  methods() ###############-->
    methods: {
      setAll(){
        let _this = this
          setSelectAll().then(res => { //查询所有未分配设备
            this.deviceList = res.result
        })
      },
      //选择未分配设备
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0);
      },
      //新建
      add() {
        this.isDisabled = false
        this.visible = true
        this.setShow = true
      },
      //删除
      onDelete (id) {//删除
        let parameter = {
          deviceId:id
        }
        //删除设备
        deleteStroeDevice(parameter).then(res=>{
          const dataSource = [...this.dataSource]
          this.dataSource = dataSource.filter(item => item.id !== id)
        })
      },
      //编辑、更多
      edit(record,itemCont) {
        this.display = true
        if(itemCont=='device'){  //设备管理
          this.mdl = Object.assign({}, record)
          this.dataSource=[]
          selectDeviceList(record.id).then(res=>{ //表格显示
            if(res.result.length>0){
              this.dataSource = res.result
            }

          })
          this.setShow =false
          this.$options.methods.setAll()
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.mdl, 'deviceId'))
          })
        }
        else { //编辑
          this.setShow =true
          if(record.area != null ||record.area != undefined){
            let str = new Array();
            let strs = record.area+"";
            str = strs.split(",")
            record.area = str;
          }
          this.mdl = Object.assign({}, record)
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.mdl, 'name', 'address','merchantId','area'))
          })
        }
        this.isDisabled = true
        this.visible = true
      },
      close() {
        this.$emit('close')
        this.visible = false
        this.form.resetFields()
        this.mdl = {}
      },
      handleOk() {
        const _this = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          // 验证表单没错误
          if (!err) {
            if(this.setShow){ //门店
              values.id = this.mdl.id
              let areas = values.area;
              let areaParam ='';
              for (let i = 0; i < areas.length ; i++) {
                if(i==areas.length-1){
                  areaParam = areaParam + areas[i]
                }else{
                  areaParam = areaParam + areas[i]+','
                }
              }
              values.area = areaParam
              save(values).then((res) => {
                if (res.code === 200) {
                  _this.$message.success('保存成功')
                  _this.$emit('ok')
                  _this.close()
                } else {
                  this.$notification.error({
                    message: '错误',
                    description: res.message,
                    duration: 4
                  })
                }
              }).catch(() => {
                // Do something
              }).finally(() => {
                _this.confirmLoading = false
              })
            }
            else { //添加设备管理
              values.storeId = _this.mdl.id
              if(!values.deviceId){
                _this.close()
                _this.$emit('ok')
                return
              }
              addStoreDevice(values).then((res)=>{
                if (res.code === 200) {
                  _this.$message.success('保存成功')
                  _this.close()
                  _this.$emit('ok')
                } else {
                  this.$notification.error({
                    message: '错误',
                    description: res.message,
                    duration: 4
                  })
                }
              }).catch(() => {
                // Do something
              }).finally(() => {
                _this.confirmLoading = false
              })

            }

          }
        })
      },
      handleCancel() {
        this.close()
      },
      onChange(value) {
      }
    },


    //--############  methods() ###############-->
  }
</script>

<style scoped>
  .editable-cell {
    position: relative;
  }

  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    line-height: 18px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell:hover .editable-cell-icon {
    display: inline-block;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
</style>
